package com.yxhl.zoume.account.presenter;

import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.EditText;

import com.yxhl.zoume.account.view.ReadSmsView;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

/**
 * Created by sugarya on 16/7/5.
 */
public class ReadSmsPresenter extends BasePresenter {

    private static final String TAG = "ReadSmsPresenter";
    //验证码长度
    private static final int VERIFY_CODE_LENGTH = 4;
    // "_id", "address", "person", "date", "type"
    private static final String[] READ_SMS_PROJECTION = new String[]{"body"};
    private static final String READ_SMS_SORT_ORDER = "date desc";
    private static Uri URI_SMS = Uri.parse("content://sms/");
    private static Uri URI_SMS_INBOX = Uri.parse("content://sms/inbox");
    private ReadSmsView mReadSmsView;

    private Context mContext;
    //显示验证码
    private EditText mSmsCodeEt;

    private ReadSmsContentObserver mReadSmsContentObserver;

    @Inject
    public ReadSmsPresenter(Context context) {
        super(context);
        mContext = context;
    }

    /**
     * 注册内容观察者
     */
    public void registerContentObserver() {
        mReadSmsContentObserver = new ReadSmsContentObserver(new Handler());
        mContext.getContentResolver().registerContentObserver(URI_SMS, true, mReadSmsContentObserver);
    }

    public void setSmsCodeEt(EditText mSmsCodeEt) {
        this.mSmsCodeEt = mSmsCodeEt;
    }

    @Override
    public void attachView(BaseView view) {
        super.attachView(view);
        if (view instanceof ReadSmsView) {
            mReadSmsView = (ReadSmsView) view;
        }
    }

    /**
     * 从数据库获取短信并过滤出验证码
     */
    private void fetchSmsCodeFromCursor(Cursor cursor) {
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String body = cursor.getString(cursor.getColumnIndex("body"));
                if (!TextUtils.isEmpty(body)) {
                    LOG.e(TAG, "body = " + body);
                    if (body.contains("走么")) {
                        String verifyCode = getSmsCode(body);
                        displayVerifyCode(verifyCode);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 显示验证码
     *
     * @param verifyCode 验证码
     */
    private void displayVerifyCode(String verifyCode) {
        mSmsCodeEt.setText(verifyCode);

        mSmsCodeEt.setFocusable(true);
        mSmsCodeEt.setFocusableInTouchMode(true);
        mSmsCodeEt.requestFocus();
        //设置光标位置
        mSmsCodeEt.setSelection(verifyCode.length());
    }

    /**
     * 从短信中获取验证码
     *
     * @param smsContent 短信内容
     * @return
     */
    private String getSmsCode(String smsContent) {
        Pattern pattern = Pattern.compile("[0-9]{4,}");
        Matcher m = pattern.matcher(smsContent);
        while (m.find()) {
            String group = m.group();
            if (group != null && group.length() >= VERIFY_CODE_LENGTH) {
                return group;
            }
        }
        return "";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReadSmsContentObserver != null) {
            ContentResolver contentResolver = mContext.getContentResolver();
            if (contentResolver != null) {
                contentResolver.unregisterContentObserver(mReadSmsContentObserver);
            }
        }
    }

    class ReadSmsContentObserver extends ContentObserver {

        public ReadSmsContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            LOG.e(TAG, "selfChange = " + selfChange);
            if (PermissionHelper.checkReadSmsPermission(mContext)) {
                mReadSmsView.initReadSmsLoader();
            } else {
                mReadSmsView.takeReadSmsPermission();
            }
        }
    }

    public class ReadSmsLoaderListener implements LoaderManager.LoaderCallbacks<Cursor> {

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            String readSmsWhere = "date >" + (System.currentTimeMillis() - 2 * 60 * 1000);
            return new CursorLoader(mContext, URI_SMS_INBOX, READ_SMS_PROJECTION, readSmsWhere, null, READ_SMS_SORT_ORDER);
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            fetchSmsCodeFromCursor(data);
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    }
}
